package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store-management/models/mysql"
	"store-management/pkg"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	name := c.GetString("name")
	mobile := c.GetString("mobile")
	password := c.GetString("password")

	var u mysql.User
	u.Name = name
	u.Mobile = mobile
	u.Password = pkg.Md5(password)

	err := u.RegisterUser(u)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"Msg":  "注册失败",
			"Code": 500,
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"Msg":  "注册成功",
		"Code": 200,
	}
	c.ServeJSON()
	return

}

func (c *UserController) Login() {
	var user mysql.User
	mobile := c.GetString("mobile")
	password := c.GetString("password")

	err := user.UserLogin(mobile)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"Msg":  "登录失败",
			"Code": 500,
		}
		c.ServeJSON()
		return
	}

	if user.Mobile != mobile {
		c.Data["json"] = map[string]interface{}{
			"Msg":  "账号不存在",
			"Code": 500,
		}
		c.ServeJSON()
		return
	}
	if user.Password != pkg.Md5(password) {
		c.Data["json"] = map[string]interface{}{
			"Msg":  "密码输入有误，请检查",
			"Code": 500,
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"Msg":  "登录成功",
		"Code": 200,
		"Data": user.ID,
	}
	c.ServeJSON()

}
